import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { getSubscribeDetails, setBookingOrder, getBookingOrder, getBookingBlog } from "../../utils/api";
let startTime: any = "08:00";
let endTime: any = "20:00";
let toDayTime: any = "";
let startMS, endMS;
let renderArr: any = [];
let needTime: any = 60;
let selectedStatu: any = [];
let id: any = 0;
let hairstylistId: any = 0;
let BookingOrder: any = [];
const BookingOrderHashMap = new Map();
let activeObj: any = {};
let blogId: any = 0;
Page({
  data: {
    date: '',
    show: false,
    renderArr: [],
    pageInfo: {},
    bookingBlog: {}
  },
  onLoad(e: any) {
    id = e.id;
    hairstylistId = e.hairstylist;
    blogId = e.blogId;
    this.onGetBookingBlog();
    this.getBookingOrders();
    this.getPageInfo(e.id);
    const time = this.formatDate(new Date());
    toDayTime = this.formatDate(new Date());
    renderArr = [];
    this.setData({
      date: time,
      renderArr: []
    }, () => {
      this.onTimePeriod();
    })
  },
  async onGetBookingBlog() {
    if (+blogId) {
      let data = await getBookingBlog({
        blogId: blogId
      })
      let tempData = data['imageUrl'] ? JSON.parse(data['imageUrl']) : JSON.parse(data['videoUrl'])
      if (data['imageUrl']) {
        data['imageUrl'] = tempData;
      } else {
        data['videoUrl'] = tempData;
      }
      this.setData({
        bookingBlog: data
      })
    }
  },
  // 提交订单
  async onSubmit() {
    await setBookingOrder({
      serviceItemsID: id,
      appointmentTime: activeObj['ms'],
      hairstylistID: hairstylistId,
      blogID: blogId
    })
    this.getBookingOrders();
    const toast: any = Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: '预约成功 3 秒后进入订单页',
      selector: '#custom-selector',
    });

    let second = 3;
    const timer = setInterval(() => {
      second--;
      if (second) {
        toast.setData({
          message: `预约成功 ${second} 秒后进入订单页`,
        });
      } else {
        clearInterval(timer);
        Toast.clear();
        wx.switchTab({
          url: "../order/order"
        })
      }
    }, 1000);
  },
  // 选中时间
  selectTime(e: any) {
    const arr: any = this.data.renderArr;
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id == e.currentTarget.dataset.id && arr[i].isOptional) {
        arr[i].isActive = true;
        activeObj = arr[i]
        break;
      } else {
        arr[i].isActive = false;
        activeObj = {}
      }
    }
    this.setData({
      renderArr: arr
    })
  },
  // 传入一个毫秒计算时间
  MSShiftTime(ms: any) {
    const h = new Date(ms).getHours() > 9 ? new Date(ms).getHours() : '0' + new Date(ms).getHours();
    const m = new Date(ms).getMinutes() > 9 ? new Date(ms).getMinutes() : '0' + new Date(ms).getMinutes();
    return h + ':' + m;
  },
  // 渲染时间段
  onTimePeriod() {
    let hours = 0; let min: any = 0;
    let ms = 0;
    renderArr = [];
    if (+new Date(this.data.date) == +new Date(toDayTime)) {
      const dt = new Date();
      hours = dt.getMinutes() > 30 ? dt.getHours() + 1 : dt.getHours();
      min = dt.getMinutes() > 30 ? '00' : 30;
      startMS = +new Date(`${this.data.date} ${hours}:${min}`);
      ms = startMS;
    } else {
      startMS = +new Date(`${this.data.date} ${startTime}`);
      ms = startMS;
    }
    endMS = +new Date(`${this.data.date} ${endTime}`);
    for (let i = 0; i < (endMS - startMS) / 1000 / 60 / 30; i++) {
      renderArr.push({
        id: i,
        ms: ms,
        startTime: this.MSShiftTime(ms),
        endTime: this.MSShiftTime(ms += (1000 * 60 * 30)),
        isOptional: true,
        isActive: false
      })
    }
    this.setData({
      renderArr: renderArr
    })
    this.changeBookingordersState();
  },
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date: any) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  onConfirm(event: any) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
    }, () => {
      this.onTimePeriod();
    });
  },
  async getPageInfo(id: any) {
    const { data } = await getSubscribeDetails({ serviceItemsID: id })
    const arr = data.shop_tb.shopBusinessTime.split("-");
    startTime = arr[0];
    endTime = arr[1];
    console.log(arr);
    this.setData({
      pageInfo: data
    })
  },
  // 获取已被预约的时间段
  async getBookingOrders() {
    BookingOrderHashMap.clear();
    const { data } = await getBookingOrder({ hairstylistID: hairstylistId })
    data.forEach((element: any) => {
      BookingOrderHashMap.set(+element['appointmentTime'], 1);
    });
    this.changeBookingordersState();
  },
  // 设置已被预约的时间端不可备选
  changeBookingordersState() {
    const arr = this.data.renderArr;
    arr.forEach((ele: any) => {
      if (BookingOrderHashMap.get(ele['ms'])) {
        ele['isOptional'] = false;
      }
    })
    this.setData({
      renderArr: arr
    })
    // BookingOrderHashMap.get(ms) ? true : false
  }
})